//
//  HLOSSManager.m
//  YueYue
//
//  Created by hulu001 on 2023/5/17.
//

#import "HLOSSManager.h"
#import "OSSWrapper.h"
#import "OSSManager.h"
#import "HLOSSTokenRequest.h"

@interface HLOSSManager ()

@property (nonatomic, strong) NSString *path;
@property (nonatomic, strong) OSSWrapper *oss; // 阿里云OSS
@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableArray *urls;
@property (nonatomic, copy) HLUploadBlock uploadSuccess;

@end

@implementation HLOSSManager


- (instancetype)initWithOSSPath:(NSString *)path
{
    self = [super init];
    if (self){
        self.path = path;
        self.urls = [NSMutableArray array];
        self.datas = [NSMutableArray array];
    }
    return self;
}


- (OSSWrapper *)oss
{
    if (!_oss) {
        _oss = [OSSWrapper.alloc init];
    }
    return _oss;
}

- (void)uploadDatas:(NSArray *)datas callBack:(HLUploadBlock)callback
{
    [self.datas removeAllObjects];
    [self.urls removeAllObjects];
    [self.datas addObjectsFromArray:datas];
    self.uploadSuccess = callback;
    [self signInAct];
}

- (void)signInAct {
    
    [QMUITips showLoading:@"上传中..." inView:[HLUIHelper keyWindow]];
    
    HLOSSTokenRequest *ossRequest = [[HLOSSTokenRequest alloc] init];
    [ossRequest startWithCompletionBlockWithSuccess:^(__kindof HLOSSTokenRequest * _Nonnull request) {
        if (request.isSuccess){
            [self config_ossWithDic:request.result];
        }
        
    } failure:^(__kindof HLOSSTokenRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        [QMUITips showWithText:request.error.localizedDescription];
    }];
}


- (void)config_ossWithDic:(NSDictionary *)dic
{
    NSString *endpoint = @"https://oss-cn-shenzhen.aliyuncs.com";
    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
        // 您需要在此处实现获取一个FederationToken，并构造成OSSFederationToken对象返回。
        // 如果由于某种原因获取失败，直接返回nil。
        OSSFederationToken * token = [[OSSFederationToken alloc] init];
        token.tAccessKey = dic[@"AccessKeyId"];
        token.tSecretKey = dic[@"AccessKeySecret"];
        token.tToken = dic[@"SecurityToken"];
        // 从您的服务器中获取token。
        return token;
    }];
    OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
    cfg.maxRetryCount = 3;
    cfg.timeoutIntervalForRequest = 15;
    cfg.isHttpdnsEnable = NO;
    cfg.crc64Verifiable = YES;

    OSSClient *defaultClient = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential clientConfiguration:cfg];
    [OSSManager sharedManager].defaultClient = defaultClient;
    
    NSString *userID = [HLLoginModel dataWithKeychain].userId;
    
    
    for (int i = 0; i < self.datas.count; i++) {
        id data = self.datas[i];
        NSString *objectKey = @"";
        NSData  *uploadData;
        
        NSString *uploadName = [[NSString stringWithFormat:@"%@-%@-%d",[HLHelper IMEI],[HLHelper getCurrentTimestamp], i + 1] qmui_md5];
        if ([data isKindOfClass:[UIImage class]]){
                UIImage *image = (UIImage *)data;
            #if DEBUG
            objectKey = [NSString stringWithFormat:@"%@/dev/%@/%@/%@.jpg",ClientID,self.path,userID,uploadName];
            #else
                objectKey = [NSString stringWithFormat:@"%@/prod/%@/%@/%@.jpg",ClientID,self.path,userID,uploadName];
            #endif
                uploadData = UIImageJPEGRepresentation(image, 0.5);
        } else if ([data isKindOfClass:[NSString class]]){
            NSString *aacPath = (NSString *)data;
            #if DEBUG
                objectKey = [NSString stringWithFormat:@"%@/dev/%@/%@/%@.aac",ClientID,self.path,userID,uploadName];
            #else
                objectKey = [NSString stringWithFormat:@"%@/prod/%@/%@/%@.aac",ClientID,self.path,userID,uploadName];
            #endif
            uploadData = [NSData dataWithContentsOfFile:aacPath options:NSDataReadingMappedAlways error:nil];
        }
        
        [self.oss asyncPutImage:objectKey localFileData:uploadData callbackParam:@{} success:^(id  _Nullable data) {
            NSString *url = [NSString stringWithFormat:@"%@%@",OSSHTTPS,objectKey];
            [self.urls addObject:url];
            
            if (self.urls.count == self.datas.count){
                [QMUITips hideAllTips];
                if (self.uploadSuccess){
                    self.uploadSuccess(self.urls.copy);
                }
            }
            
        } failure:^(NSError * _Nullable error) {
            [QMUITips hideAllTips];
            [QMUITips showWithText:error.localizedDescription];
        }];
    }
}

@end
